/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tools;

import com.openbrew.openbrewrf.HopContract;
import com.openbrew.openbrewrf.Hops;
import com.openbrew.openbrewrf.PurchaseOrder;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

/**
 *
 * @author chapmand
 */
public class HopContractTools {
    public void updateContracts(final EntityManager en, final int qty, final int hopID, final PurchaseOrder po){
        TypedQuery<Hops> query = en.createQuery(
            "SELECT h FROM Hops h WHERE h.hid = ?1", Hops.class);
        query.setParameter(1, hopID);
        Hops hop = query.getSingleResult();
        final int date = po.getPODate().getYear();
        for(HopContract hc : getContracts(en, hop)){
            final int year = hc.getHopContractYear().getYear();
            if(date >= year){
                if(hc.getContractLbsLeft()>0){
                    final float totalqty = qty * hop.getHopBagLbs();
                    float newqty = hc.getContractLbsLeft() - totalqty;
                    if(newqty < 0){
                        newqty = 0;
                    }
                    hc.setContractLbsLeft(newqty);
                    return;
                }
            }
        }
    }
    
    private List<HopContract> getContracts(final EntityManager en, final Hops hop){
        TypedQuery<HopContract> query = en.createQuery(
            "SELECT hc FROM HopContract hc WHERE hc.hopID.hid = ?1", HopContract.class);
        query.setParameter(1, hop.getHid());
        return query.getResultList();
    }
}
